package com.smile.utils;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

 class JwtUtils {

    val TOKEN_TIME_OUT =  60 * 60 * 1000 * 24;

    var TOKEN_SECRET_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";

     public fun createToken(username: String, id: String) : String{
        var jwtBuilder = Jwts.builder();
        var token  = jwtBuilder
                .setHeaderParams(mapOf(
                    "typ" to "JWT",
                    "alg" to "HS256"
                ))
                .setSubject("subject")
                .addClaims(mapOf("username" to username))
                .setExpiration(Date(System.currentTimeMillis() + TOKEN_TIME_OUT))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256,TOKEN_SECRET_KEY)
                .compact();
        return token;
    }

    public fun verifyToken(token: String) : String{
        var jwtParser = Jwts.parser();
        var claimsJws : Jws<Claims> = jwtParser.setSigningKey(TOKEN_SECRET_KEY).parseClaimsJws(token);
        var claims  : Claims = claimsJws.getBody();
        var username  = claims.get("username");
//        Object id = claims.get("id");
//        HashMap<String, String> map = new HashMap<>();
//        map.put("username",username.toString());
//        map.put("id",id.toString());
        return username.toString();
    }

     companion object {
         fun createToken(username: String, id: Any): String {
             var jwtBuilder = Jwts.builder();
             var token  = jwtBuilder
                 .setHeaderParams(mapOf(
                     "typ" to "JWT",
                     "alg" to "HS256"
                 ))
                 .setSubject("subject")
                 .addClaims(mapOf("username" to username))
                 .setExpiration(Date(System.currentTimeMillis() + 60 * 60 * 1000 * 24))
                 .setId(UUID.randomUUID().toString())
                 .signWith(SignatureAlgorithm.HS256,"MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY")
                 .compact();
             return token;
         }
     }

 }
